package cn.jhc.transport.service;

import android.util.Log;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;

import cn.jhc.transport.bean.Environment;
import cn.jhc.transport.bean.TrafficLightConfig;

/**
 * Created by luyanfei on 16-2-21.
 */
public class TransportService {
    public static final String TAG = "TransportTag";
    private static final String URL_PREFIX = "http://10.2.51.151:8080/transportservice/type/jason/action/";

    public static int getCarSpeed(int carId) throws IOException, JSONException {
        String url = URL_PREFIX + "GetCarSpeed.do";
        String content = "{\"CarId\":" + carId + "}";
        JSONObject res = post(url, content);
        int speed = res.getInt("CarSpeed");
        return speed;
    }

    public static boolean setCarMove(int carId, String carAction) {

        return false;
    }

    public static TrafficLightConfig getTrafficLightConfigAction(int trafficLightId){

        return null;
    }

    public static Environment getAllSense() throws IOException, JSONException {
        String url = URL_PREFIX + "GetAllSense.do";
        JSONObject object = post(url,"");
        Environment env = new Environment();
        env.setCo2(object.getInt("co2"));
        env.setHumidity(object.getInt("humidity"));
        env.setLightIntensity(object.getInt("LightIntensity"));
        env.setPm25(object.getInt("pm2.5"));
        env.setTemp(object.getInt("temperature"));
        return env;
    }

    public static JSONObject post(String url, String content) throws IOException, JSONException {
        Log.d(TAG, "Request for: " + url + ". With content: " + content);
        URL requestUrl = new URL(url);
        HttpURLConnection conn = (HttpURLConnection)requestUrl.openConnection();
        conn.setRequestProperty("Content-Type", "application/json");
        conn.setDoOutput(true);
        conn.setFixedLengthStreamingMode(content.length());
        PrintWriter output = new PrintWriter(
                new OutputStreamWriter(new BufferedOutputStream(
                conn.getOutputStream())));
        output.print(content);
        output.flush();

        BufferedReader reader = new BufferedReader(
                new InputStreamReader(conn.getInputStream())
        );
        StringBuilder stringBuilder = new StringBuilder();
        String line;
        while( (line = reader.readLine()) != null){
            stringBuilder.append(line);
        }
        String result = stringBuilder.toString();
        Log.d(TAG,"Response:" + result);
        conn.disconnect();
        JSONObject obj = new JSONObject(result);
        String info = obj.getString("serverinfo");
        return new JSONObject(info);
    }
}
